#include "cCustomFuncHelper.h"
#include <time.h>
#include <stdlib.h>
#include <algorithm>

namespace libcvos_vfr
{
	namespace Helper
	{

		bool Tool_CheckIfFileNameIntheList(std::list<std::string> &fileNameList, std::string fileName, std::mutex &Lock)
		{
			bool bRet = false;
			std::lock_guard<std::mutex> locker(Lock);

			if (!fileNameList.empty()
				&& !fileName.empty())
			{
				auto FindResult = std::find(std::begin(fileNameList), std::end(fileNameList), fileName);
				if (FindResult != std::end(fileNameList))
				{
					bRet = true;
				}
			}

			return bRet;
		}

		bool Tool_AddFileNameToTheList(std::list<std::string> &fileNameList, std::string fileName, std::mutex &pCsLock, std::string::size_type maxListSize)
		{
			bool bRet = false;
			std::lock_guard<std::mutex> locker(pCsLock);

			if (maxListSize > 0
				&& !fileName.empty())
			{
				if (fileNameList.size() >= maxListSize)
				{
					fileNameList.pop_front();
					//printf("%s list size %d is larger than maxSize %d,remove the first one", __FUNCTION__,  fileNameList.size(), maxListSize);
				}
				fileNameList.push_back(fileName);
				bRet = true;
			}

			return bRet;
		}

#ifdef _WIN32
		int Tool_SafeCloseThread(HANDLE& threadHandle)
		{
			if (threadHandle == NULL)
			{
				return -1;
			}
			MSG msg;
			DWORD dwRet = -1;
			while (NULL != threadHandle && WAIT_OBJECT_0 != dwRet) // INFINITE
			{
				dwRet = MsgWaitForMultipleObjects(1, &threadHandle, FALSE, 100, QS_ALLINPUT);
				if (dwRet == WAIT_OBJECT_0 + 1)
				{
					if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
					{
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
				}
			}
			CloseHandle(threadHandle);
			threadHandle = NULL;
            return 0;
        }

#endif // WIN32

        int Tool_GetRanNum()
        {
            int iRandNum = 0;
            srand((unsigned)time(NULL));
            iRandNum = rand() +1;
            return iRandNum;
        }

	}
}
